<template>
  <div class="shop">
    <main class="container">
      <div class="shop-header">
        <h2>熊猫商城</h2>
        <p>购买可爱的熊猫周边产品，部分收益将用于熊猫保护事业，让您的每一笔消费都有意义。</p>
      </div>
      
      <div class="shop-banner">
        <div class="banner-content">
          <h3>熊猫限定款周边</h3>
          <p>庆祝熊猫宝宝诞生特别系列，限量发售</p>
          <button class="banner-btn" @click="scrollToProducts">立即抢购</button>
        </div>
      </div>
      
      <div class="shop-categories">
        <div 
          v-for="category in categories" 
          :key="category.id"
          class="category-btn"
          :class="{ active: currentCategory === category.id }"
          @click="selectCategory(category.id)"
        >
          {{ category.name }}
        </div>
      </div>
      
      <div class="product-grid">
        <div v-for="product in filteredProducts" :key="product.id" class="product-card">
          <div v-if="product.badge" class="product-badge">{{ product.badge }}</div>
          <img :src="product.image" :alt="product.name" class="product-image">
          <div class="product-info">
            <h3>{{ product.name }}</h3>
            <div class="product-price">
              ¥{{ product.price }}
              <span v-if="product.originalPrice" class="product-original-price">¥{{ product.originalPrice }}</span>
            </div>
            <div class="product-rating">
              {{ getRatingStars(product.rating) }}
              <span>({{ product.reviewCount }})</span>
            </div>
            <div class="product-actions">
              <button class="add-to-cart" @click="addToCart(product)">加入购物车</button>
              <button 
                class="wishlist-btn"
                :class="{ active: product.isWishlisted }"
                @click="toggleWishlist(product)"
              >
                ❤
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <div class="cart-summary" @click="showCart">
        🛒
        <div class="cart-count" v-if="cartItemCount > 0">{{ cartItemCount }}</div>
      </div>
    </main>
    
    <!-- 购物车抽屉 -->
    <el-drawer
      v-model="cartDrawerVisible"
      title="购物车"
      direction="rtl"
      size="400px"
    >
      <div v-if="cartItems.length > 0">
        <div v-for="item in cartItems" :key="item.id" class="cart-item">
          <img :src="item.image" :alt="item.name" class="cart-item-image">
          <div class="cart-item-info">
            <h4>{{ item.name }}</h4>
            <div class="cart-item-price">¥{{ item.price }}</div>
            <div class="cart-item-quantity">
              <button @click="decreaseQuantity(item)">-</button>
              <span>{{ item.quantity }}</span>
              <button @click="increaseQuantity(item)">+</button>
            </div>
          </div>
          <button class="remove-item" @click="removeFromCart(item)">×</button>
        </div>
        
        <div class="cart-summary">
          <div class="total-price">
            总计: <span>¥{{ totalPrice }}</span>
          </div>
          <el-button type="primary" @click="checkout" :disabled="!isLoggedIn">
            {{ isLoggedIn ? '结算' : '请先登录' }}
          </el-button>
        </div>
      </div>
      <div v-else class="empty-cart">
        <el-empty description="购物车是空的" />
      </div>
    </el-drawer>
  </div>
</template>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.shop-header {
  margin: 40px 0 30px;
  text-align: center;
}

.shop-header h2 {
  font-size: 28px;
  color: var(--primary-color);
  margin-bottom: 15px;
}

.shop-header p {
  color: #666;
  max-width: 700px;
  margin: 0 auto;
  line-height: 1.6;
}

.shop-banner {
  height: 300px;
  background-color: #eee;
  border-radius: 15px;
  margin: 30px 0;
  background-image: url('@/assets/shop-banner.jpg');
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-align: center;
  position: relative;
}

.shop-banner::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  border-radius: 15px;
}

.banner-content {
  position: relative;
  z-index: 1;
  padding: 20px;
}

.banner-content h3 {
  font-size: 36px;
  margin-bottom: 15px;
}

.banner-content p {
  font-size: 18px;
  margin-bottom: 20px;
}

.banner-btn {
  display: inline-block;
  padding: 12px 30px;
  background-color: var(--secondary-color);
  color: white;
  border: none;
  border-radius: 30px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
  text-decoration: none;
}

.banner-btn:hover {
  background-color: #3e8e41;
  transform: translateY(-2px);
}

.shop-categories {
  display: flex;
  gap: 15px;
  margin: 30px 0;
  overflow-x: auto;
  padding-bottom: 10px;
}

.category-btn {
  padding: 10px 20px;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 30px;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.category-btn:hover, .category-btn.active {
  background-color: var(--secondary-color);
  color: white;
  border-color: var(--secondary-color);
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 25px;
  margin: 40px 0;
}

.product-card {
  background-color: white;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
  position: relative;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.product-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: var(--accent-color);
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 12px;
  font-weight: bold;
  z-index: 1;
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.product-info {
  padding: 20px;
}

.product-info h3 {
  font-size: 18px;
  margin-bottom: 10px;
  color: var(--primary-color);
}

.product-price {
  font-size: 20px;
  font-weight: bold;
  color: var(--secondary-color);
  margin-bottom: 15px;
}

.product-original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
  margin-left: 5px;
}

.product-rating {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 15px;
  color: #FF9800;
}

.product-actions {
  display: flex;
  gap: 10px;
}

.add-to-cart {
  flex: 1;
  padding: 8px 0;
  background-color: var(--secondary-color);
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
}

.add-to-cart:hover {
  background-color: #3e8e41;
}

.wishlist-btn {
  width: 40px;
  height: 40px;
  background-color: #f5f5f5;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.wishlist-btn:hover, .wishlist-btn.active {
  background-color: #ffebee;
  color: #f44336;
}

.cart-summary {
  position: fixed;
  bottom: 30px;
  right: 30px;
  background-color: var(--secondary-color);
  color: white;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  transition: all 0.3s;
  z-index: 10;
}

.cart-summary:hover {
  transform: translateY(-5px);
}

.cart-count {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: var(--accent-color);
  color: white;
  width: 25px;
  height: 25px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.cart-item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 15px;
}

.cart-item-info {
  flex: 1;
}

.cart-item-info h4 {
  margin-bottom: 5px;
  font-size: 16px;
}

.cart-item-price {
  color: var(--secondary-color);
  font-weight: bold;
  margin-bottom: 10px;
}

.cart-item-quantity {
  display: flex;
  align-items: center;
  gap: 10px;
}

.cart-item-quantity button {
  width: 25px;
  height: 25px;
  border: 1px solid #ddd;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
}

.cart-item-quantity span {
  min-width: 30px;
  text-align: center;
}

.remove-item {
  width: 30px;
  height: 30px;
  border: none;
  background-color: #f5f5f5;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #999;
  transition: all 0.3s;
}

.remove-item:hover {
  background-color: #ffebee;
  color: #f44336;
}

.cart-summary {
  padding: 20px;
  border-top: 1px solid #eee;
}

.total-price {
  font-size: 18px;
  margin-bottom: 15px;
}

.total-price span {
  color: var(--secondary-color);
  font-weight: bold;
}

.empty-cart {
  padding: 40px 0;
}
</style>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import apiService from '@/services/api.service'

const router = useRouter()
const isLoggedIn = ref(false)
const userAvatar = ref('')
const currentCategory = ref('全部商品')
const cartDrawerVisible = ref(false)

const categories = ref([])
const products = ref([])
const cartItems = ref([])
const loading = ref(false)

const filteredProducts = computed(() => {
  if (currentCategory.value === '全部商品') {
    return products.value
  }
  return products.value.filter(product => product.category === currentCategory.value)
})

const cartItemCount = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.price * item.quantity, 0)
})

onMounted(() => {
  checkLoginStatus()
  fetchProducts()
  fetchCategories()
  if (isLoggedIn.value) {
    fetchCartItems()
  }
})

const checkLoginStatus = () => {
  const token = localStorage.getItem('token')
  if (token) {
    isLoggedIn.value = true
    fetchUserInfo()
  }
}

const fetchUserInfo = async () => {
  try {
    const response = await fetch('/api/user/info', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    if (response.ok) {
      const data = await response.json()
      userAvatar.value = data.avatar || '/images/default-avatar.jpg'
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

const handleLogout = () => {
  localStorage.removeItem('token')
  isLoggedIn.value = false
  ElMessage.success('退出登录成功')
  router.push('/login')
}

const goToProfile = () => {
  router.push('/user')
}

const goToDocuments = () => {
  router.push('/documents')
}

const selectCategory = (categoryId) => {
  currentCategory.value = categoryId
}

const scrollToProducts = () => {
  const productsSection = document.querySelector('.product-grid')
  if (productsSection) {
    productsSection.scrollIntoView({ behavior: 'smooth' })
  }
}

const getRatingStars = (rating) => {
  return '★'.repeat(rating) + '☆'.repeat(5 - rating)
}

const fetchProducts = async () => {
  loading.value = true
  try {
    const response = await apiService.getProducts()
    if (response.success) {
      products.value = response.data
    } else {
      ElMessage.error(response.message || '获取商品列表失败')
    }
  } catch (error) {
    ElMessage.error('获取商品列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const fetchCategories = async () => {
  loading.value = true
  try {
    const response = await apiService.getCategories()
    if (response.success) {
      categories.value = response.data
    } else {
      ElMessage.error(response.message || '获取分类列表失败')
    }
  } catch (error) {
    ElMessage.error('获取分类列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const fetchCartItems = async () => {
  if (!localStorage.getItem('token')) return

  try {
    const response = await apiService.getCartItems()
    if (response.success) {
      cartItems.value = response.data
    }
  } catch (error) {
    console.error('获取购物车失败:', error)
  }
}

const addToCart = async (product) => {
  if (!localStorage.getItem('token')) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    const response = await apiService.addToCart(product.id, 1)
    if (response.success) {
      ElMessage.success('已添加到购物车')
      fetchCartItems()
    } else {
      ElMessage.error(response.message || '添加失败')
    }
  } catch (error) {
    ElMessage.error('添加失败，请稍后重试')
  }
}

const toggleWishlist = async (product) => {
  if (!localStorage.getItem('token')) {
    ElMessage.warning('请先登录后再收藏')
    router.push('/login')
    return
  }

  try {
    const response = await apiService.addToWishlist(product.id)
    if (response.success) {
      product.isWishlisted = !product.isWishlisted
      ElMessage.success(product.isWishlisted ? '已添加到收藏' : '已取消收藏')
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const increaseQuantity = async (item) => {
  try {
    const response = await apiService.updateCartItem(item.id, { quantity: item.quantity + 1 })
    if (response.success) {
      item.quantity++
    }
  } catch (error) {
    ElMessage.error('更新数量失败')
  }
}

const decreaseQuantity = async (item) => {
  if (item.quantity > 1) {
    try {
      const response = await apiService.updateCartItem(item.id, { quantity: item.quantity - 1 })
      if (response.success) {
        item.quantity--
      }
    } catch (error) {
      ElMessage.error('更新数量失败')
    }
  }
}

const removeFromCart = async (item) => {
  try {
    const response = await apiService.removeCartItem(item.id)
    if (response.success) {
      const index = cartItems.value.indexOf(item)
      if (index > -1) {
        cartItems.value.splice(index, 1)
      }
    }
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const checkout = async () => {
  if (!localStorage.getItem('token')) {
    ElMessage.warning('请先登录后再结算')
    router.push('/login')
    return
  }

  try {
    const response = await apiService.checkout()
    if (response.success) {
      ElMessage.success('下单成功')
      cartItems.value = []
      cartDrawerVisible.value = false
    } else {
      ElMessage.error(response.message || '下单失败')
    }
  } catch (error) {
    ElMessage.error('下单失败')
  }
}

const showCart = () => {
  cartDrawerVisible.value = true
}
</script> 